package com.xhs.annotation.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Set;

/**
 * @desc： 全局异常处理
 * @author： xhs
 * @date： 2021/5/24 14:23
 * @version： JDK 1.8
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler
    public HashMap<String, Object> exceptionHandler(Exception e) {
        log.info(">>>>>>>>>>>>>>>>>>全局异常：{}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", e.getMessage());
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", 500);
        map.put("msg", "系统处理失败，请联系管理员");
        return map;
    }

    /**
     * JSON格式参数校验失败
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public HashMap<String, Object> validateHandlerJson(MethodArgumentNotValidException e) {
        log.info(">>>>>>>>>>>>>>>>>>JSON格式参数校验失败：{}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", e.getMessage());
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", 500);
        map.put("msg", "参数校验失败");
        map.put("msg", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return map;
    }

    /**
     * 单个参数校验失败
     *
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public HashMap<String, Object> validateHandler(ConstraintViolationException e) {
        log.info(">>>>>>>>>>>>>>>>>>单个参数校验失败：{}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", e.getMessage());
        StringBuilder errorInfo = new StringBuilder();
        String errorMessage;
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> item : violations) {
            errorInfo.append(item.getMessage()).append(",");
        }
        errorMessage = errorInfo.toString().substring(0, errorInfo.toString().length() - 1);
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("code", 500);
        map.put("msg", errorMessage);
        return map;
    }
}
